package bb.lanxing.mvp.model;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import com.alibaba.fastjson.JSON;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;

import android.text.TextUtils;

import bb.lanxing.App;
import bb.lanxing.model.bean.PlaceComment;
import bb.lanxing.model.Comment;
import bb.lanxing.model.database.PostQueue;
import bb.lanxing.model.json.RouteBookComment;
import bb.lanxing.model.json.Topic;
import bb.lanxing.model.json.WorkoutComment;
import bb.lanxing.model.json.club.ClubNews;
import bb.lanxing.model.json.club.NewsComment;
import bb.lanxing.model.json.club.PostClubNews;
import bb.lanxing.mvp.presetner.ClubPresenter;
import bb.lanxing.mvp.presetner.i.IPostQueueModel;
import bb.lanxing.network.BiCiCallback;
//import bb.lanxing.network.BiciHttpClient;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetSubscribe;
import bb.lanxing.util.ImageUtil;
import bb.lanxing.util.Log;
import rx.Observable;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class PostQueueModelImpl implements IPostQueueModel {
    @Override
    public void resetState(int oldState, int newState) {

        LitePal.getDatabase().execSQL("update postqueue set state=? where state=?",
                new Integer[] { newState, oldState });

        // SugarRecord.getSugarDb().getDB().execSQL("update POST_QUEUE set state=? where state=?", new
        // Integer[]{Integer.valueOf(i2), Integer.valueOf(i)});
    }

    @Override
    public List<PostQueue> getNeedSendList() {
        List<PostQueue> l = LitePal.where("state != 1").find(PostQueue.class);
        return l;

        // return SugarRecord.find(PostQueue.class, "STATE<>1");
    }

    @Override
    public Observable<List<PostQueue>> getList(int i) {
        return Observable.just(i).subscribeOn(Schedulers.io())
                .flatMap((Func1<Integer, Observable<List<PostQueue>>>) num -> Observable
                        .just(LitePal.where("state=?", String.valueOf(num)).find(PostQueue.class)));

        // .just(SugarRecord.find(PostQueue.class, "STATE=?", String.valueOf(num))));
    }

    @Override
    public Observable<Boolean> sendTopic(PostQueue postQueue) {
        Topic topic = (Topic) JSON.parseObject(postQueue.getContent(), Topic.class);
        return Observable
                .create(new NetSubscribe(
                        MyHttpClient.createTopic((int) topic.getChannelId(), topic.getTitle(), topic.getContent(),
                                postQueue.getImages(), new LatLng(topic.getLatitude(), topic.getLongitude()))))
                .subscribeOn(Schedulers.io())
                .flatMap((Func1<String, Observable<Boolean>>) str -> Observable.just(true));
    }

    @Override
    public Observable<Boolean> sendTopicComment(PostQueue postQueue) {
        Comment comment = (Comment) JSON.parseObject(postQueue.getContent(), Comment.class);
        return Observable
                .create(new NetSubscribe(MyHttpClient.createComment(comment.getTopic(), comment.getContent(),
                        comment.getInformedUserId(), postQueue.getImages(),
                        new LatLng(comment.getLatitude(), comment.getLongitude()))))
                .subscribeOn(Schedulers.io())
                .flatMap((Func1<String, Observable<Boolean>>) str -> Observable.just(true));
    }

    @Override
    public Observable<Boolean> sendClubNotice(PostQueue postQueue) {
        ClubNews parseNews = ClubPresenter.getInstance().parseNews(postQueue.getContent());
        return Observable
                .create(new NetSubscribe(
                        MyHttpClient.postAnnouncement(new PostClubNews(0, parseNews.getContent().toString(),
                                parseNews.getTeamId(), 0L, null, 0L, postQueue.getImages()))))
                .subscribeOn(Schedulers.io())
                .flatMap((Func1<String, Observable<Boolean>>) str -> Observable.just(true));
    }

    @Override
    public Observable<Boolean> sendClubComment(PostQueue postQueue) {
        NewsComment newsComment = JSON.parseObject(postQueue.getContent(), NewsComment.class);
        return Observable
                .create(new NetSubscribe(MyHttpClient.postReply(new PostClubNews(1, newsComment.getContent(),
                        newsComment.getTeamId(), newsComment.getInformedUserId(), newsComment.getInformedUserName(),
                        newsComment.getFlowId(), newsComment.getUserPicUrl()))))
                .subscribeOn(Schedulers.io())
                .flatMap((Func1<String, Observable<Boolean>>) str -> Observable.just(true));
    }

    @Override
    public Observable<Boolean> sendWorkoutComment(PostQueue postQueue) {
        WorkoutComment workoutComment = JSON.parseObject(postQueue.getContent(), WorkoutComment.class);
        return Observable
                .create(new NetSubscribe(MyHttpClient.setWorkoutComment(workoutComment.getWorkoutId(),
                        workoutComment.getContent(), workoutComment.getImage(), workoutComment.getInformedId())))
                .subscribeOn(Schedulers.io())
                .flatMap((Func1<String, Observable<Boolean>>) str -> Observable.just(true));
    }

    @Override
    public Observable<Boolean> sendLushuComment(PostQueue postQueue) {
        RouteBookComment routeBookComment = JSON.parseObject(postQueue.getContent(), RouteBookComment.class);
        return Observable
                .create(new NetSubscribe(MyHttpClient.commentLushu(postQueue.getSubId(), routeBookComment.getContent(),
                        postQueue.getImages(), routeBookComment.getInformedUserId())))
                .subscribeOn(Schedulers.io()).flatMap((Func1<String, Observable<Boolean>>) str -> {
                    try {
                        JSONObject jSONObject = new JSONObject(str);
                        if (jSONObject.getInt("code") == 200) {
                            return Observable.just(true);
                        }
                        String string =
                                jSONObject.getString(SDKInitializer.SDK_BROADTCAST_INTENT_EXTRA_INFO_KEY_ERROR_MESSAGE);
                        if (!TextUtils.isEmpty(string)) {
                            App.getContext().showMessage(string);
                        }
                        return Observable.just(false);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        return Observable.just(false);
                    }
                });
    }

    @Override
    public Observable<Boolean> sendShopComment(PostQueue postQueue) {
        PlaceComment placeComment = JSON.parseObject(postQueue.getContent(), PlaceComment.class);
        return Observable
                .create(new NetSubscribe(MyHttpClient.addBikePlaceComment(placeComment.getId(),
                        placeComment.getContent(), postQueue.getImages(), 3, placeComment.getInformedUserId())))
                .subscribeOn(Schedulers.io()).flatMap((Func1<String, Observable<Boolean>>) str -> {
                    boolean z = false;
                    try {
                        if (new JSONObject(str).getInt(BiCiCallback.RESPONSE_RES) == 1) {
                            z = true;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    return Observable.just(z);
                });
    }

    // TODO: 2024/6/26 send comments with image,need add interface, author:sunjw
    @Override
    public String uploadImage(String str, int i) {
        // try {
        // String uploadToUPYun = UpYunUtils.uploadToUPYun(str, getUPYunImagePath(i));
        // return Constants.UPYUN_HOST + uploadToUPYun;
        // } catch (UpYunException unused) {
        // return null;
        // }
        return null;
    }

    @Override
    public Observable<List<PostQueue>> getTypedPostQueue(int i, final long j, final boolean z) {
        return Observable.just(i).subscribeOn(Schedulers.io())
                .flatMap((Func1<Integer, Observable<List<PostQueue>>>) num -> Observable
                        .just(PostQueueModelImpl.this.getTypedPostQueueSync(num, j, z)));
    }

    @Override
    public List<PostQueue> getTypedPostQueueSync(int type, long subId, boolean z) {
        if (subId > 0) {
            String[] strArr = { String.valueOf(type), String.valueOf(subId) };
            StringBuilder sb = new StringBuilder();
            sb.append("createTime");
            sb.append(z ? " ASC" : " DESC");
            long currentTimeMillis = System.currentTimeMillis();
            List<PostQueue> l = LitePal.where("type=? AND subId=?", String.valueOf(type), String.valueOf(subId))
                    .order(sb.toString()).find(PostQueue.class);
            long useTime = System.currentTimeMillis() - currentTimeMillis;
            Log.i("PostQueueModelImpl", "getTypedPostQueueSync check List<PostQueue> useTime=" + useTime + "ms");
            return l;

            // return SugarRecord.find(PostQueue.class, "TYPE=? AND SUB_ID=?", strArr, null, sb.toString(), null);
        }
        String[] strArr2 = { String.valueOf(type) };
        StringBuilder sb2 = new StringBuilder();
        sb2.append("createTime");
        sb2.append(z ? " ASC" : " DESC");

        List<PostQueue> l = LitePal.where("type=?", String.valueOf(type)).order(sb2.toString()).find(PostQueue.class);
        return l;

        // return SugarRecord.find(PostQueue.class, "TYPE=?", strArr2, null, sb2.toString(), null);
    }

    @Override
    public boolean isDataValid(PostQueue data) {
        Long id = data.getId();
        if (id != null) {
            PostQueue p = LitePal.where("id=?", String.valueOf(id)).findFirst(PostQueue.class);
            return p != null;
        } else {
            return true;
        }
        // return data.getId() == null || SugarRecord.findById(PostQueue.class, data.getId()) != null;
    }

    private String getUPYunImagePath(int i) {
        if (i != 1) {
            if (i != 2) {
                if (i != 4) {
                    if (i != 32) {
                        if (i != 64) {
                            return null;
                        }
                        return ImageUtil.buildBikePlaceCommentImagePath();
                    }
                    return ImageUtil.buildLushuCommentImagePath();
                }
                return ImageUtil.buildClubcImagePath();
            }
            return ImageUtil.buildTopicCommentImagePath();
        }
        return ImageUtil.buildTopicImagePath();
    }
}
